import 'package:flutter/services.dart';
import 'package:fluwx/fluwx.dart' as fluwx;
import 'package:gm_login_plugin/gm_login_plugin.dart';
import 'package:riki_login/res/header.dart';

///作者：范玉辉
///创建时间：2021/7/22
///说明：

class LoginWeichatAuth {
  // 微信授权

  static const MethodChannel channel = MethodChannel('MBProgressPlugin');

  static initWeiChatSDK() async {
    await fluwx.registerWxApi(
      appId: RikiLogin.instance.wechatAppId,
      doOnAndroid: true,
      doOnIOS: true,
      universalLink: RikiLogin.instance.wechatUniversalLink,
    );

    await isInstalled(isInit: true);

    // 监听微信sdk授权结果回调，将授权结果通知登录sdk
    fluwx.weChatResponseEventHandler.distinct((a, b) => a == b).listen((res) {
      if (res is fluwx.WeChatAuthResponse) {
        fluwx.WeChatAuthResponse authResponse = res;
        print(authResponse);
        Map<String, dynamic> response = {};
        response["code"] = authResponse.code;
        response["state"] = authResponse.state;

        GMAuthResponse responseModel = GMAuthResponse(
          isSuccessed: authResponse.code == "0",
          failCode: authResponse.errCode,
          failReason: authResponse.errStr,
          response: response,
        );
        GMLoginPlugin.authResponse(responseModel);
      }
    });
  }

  static Future<bool> isInstalled({bool isInit = false}) async {
    bool isInstall = await fluwx.isWeChatInstalled;
    GMLoginPlugin.setIsInstalled(isInstall, GMESurpportPlatform.wechart);
    if (!isInstall && !isInit) {
      LoginWeichatAuth.channel.invokeListMethod('showText',{'text': '您还没有安装微信'});
    }
    return isInstall;
  }

  static Future sendWeiChatAuth() async {
    return await fluwx.sendWeChatAuth(
      scope: RikiLogin.instance.gmWechatScope,
      state: RikiLogin.instance.gmWechatState,
    );
  }
}
